<template>
  <div id="test"></div>
  <tools
    id="welcome"
    :msg="msg"
    @BackHome="ResetView"
    @JustifyHeight="JustifyHeight"
    @LookAtChange="LookAtChange"
  />
</template>

<script>
import { onMounted, ref} from "vue";
import Tools from "./components/Tools.vue";
import { ElMessage } from "element-plus";

export default {
  name: "App",
  components: { Tools },
  setup() {
    const OSGBOffsetHeight = -30;
    const tiandituTk = "65c2b9601a426da48fe63780deaf2480";
    let msg = ref("场地污染测试Demo");

    function Initialize() {
      // let subdomains =  ["0", "1", "2", "3", "4", "5", "6", "7"];
      let viewer = window.viewer = new Cesium.Viewer("test", {
        terrainProvider: Cesium.createWorldTerrain({
          requestWaterMask: true,
          requestVertexNormals: true, // 顶点(vertex)法线(normal)可加载光影效果
        }),
        // imageryProvider:new Cesium.WebMapTileServiceImageryProvider({
        //   url:
        //     "http://t{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
        //     tiandituTk,
        //   subdomains: subdomains,
        //   layer: "tdtImgLayer",
        //   style: "default",
        //   format: "image/jpeg",
        //   tileMatrixSetID: "GoogleMapsCompatible",
        //   show: true,
        // })

      });

      // 天地图底图
      // this.baseLayer = viewer.imageryLayers.addImageryProvider(
      //   new Cesium.WebMapTileServiceImageryProvider({
      //     url:
      //       "http://t{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
      //       tiandituTk,
      //     subdomains: subdomains,
      //     layer: "tdtImgLayer",
      //     style: "default",
      //     format: "image/jpeg",
      //     tileMatrixSetID: "GoogleMapsCompatible",
      //     show: true,
      //   })
      // );

      // 天地文本注记
      viewer.imageryLayers.addImageryProvider(
        new Cesium.WebMapTileServiceImageryProvider({
          url:
            "http://t0.tianditu.com/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
            tiandituTk,
          layer: "tdtAnnoLayer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "GoogleMapsCompatible",
          show: true,
        })
      );

      // 模型 115.94375972865149,39.75301672911576
      LoadModel(
        "/static/models/nomanrobot.glb",
        99.9053498394261,
        22.578622007485787,
        996.1512649827818,
        0,
        -0.2,
        0
      );

      //倾斜摄影
      // LoadingOSGB();

      // ResetView(true);
      ClickShowPosition();
    }

    const ResetView = () => {
      window.viewer.scene.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
      window.viewer.scene.camera.flyTo({
        //镜头的经纬度、高度。镜头默认情况下，在指定经纬高度俯视（pitch=-90）地球
        destination: Cesium.Cartesian3.fromDegrees(99.908982, 22.590135, 5900),
        //destination:Cesium.Cartesian3.fromDegrees(115.944969 , 39.7532944, 1000),
        // orientation: {
        //   heading: Cesium.Math.toRadians(-15),
        //   pitch: Cesium.Math.toRadians(-25),
        //   roll: Cesium.Math.toRadians(0),
        // },
        duration: 5, //动画持续时间：秒
      });
    };

    const LoadingOSGB = () => {
      let viewer = window.viewer;
      let heightOffset = OSGBOffsetHeight; // 调整高差：米
      let tileset = new Cesium.Cesium3DTileset({
        url: "/api/cesiumtest/3dtiles/light/tileset.json",
        //url: "./static/clips/tileset.json",
        type: "3dtiles",
        maximumScreenSpaceError: 20,
        maximumNumberOfLoadedTiles: 10, //最大加载瓦片个数
      });
      tileset._modelMatrix = Cesium.Matrix4.fromTranslation(
        Cesium.Cartesian3.fromArray([0, 0, heightOffset])
      );
      tileset.allTilesLoaded.addEventListener(() => {
        //viewer.zoomTo(tileset);
        //this.ResetView();
      });

      tileset.readyPromise.then(function(tileset) {
        viewer.scene.primitives.add(tileset); // 添加到场景
        window.osgb_tileset = tileset;
      });
    };

    function JustifyHeight(heightOffset) {
      let tileset = window.osgb_tileset;
      let matrix = tileset._root.transform;
      matrix[14] += heightOffset;
    }

    function LoadModel(url, longitude, latitude, height, heading, pitch, roll) {
      let viewer = window.viewer;
      let scene = viewer.scene;
      height = Cesium.defaultValue(height, 0.0);
      heading = Cesium.defaultValue(heading, 0.0);
      pitch = Cesium.defaultValue(pitch, 0.0);
      roll = Cesium.defaultValue(roll, 0.0);
      var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
      var origin = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
      var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(
        origin,
        hpr
      );
      let model = scene.primitives.add(
        Cesium.Model.fromGltf({
          url: url,
          modelMatrix: modelMatrix,
          minimumPixelSize: 28,
        })
      );
      window.model = model;
      model.readyPromise
        .then((model) => {
          var camera = viewer.camera;
          var controller = scene.screenSpaceCameraController;
          var r =
            2.0 * Math.max(model.boundingSphere.radius, camera.frustum.near);
          controller.minimumZoomDistance = r * 0.5;

          var center = Cesium.Matrix4.multiplyByPoint(
            model.modelMatrix,
            model.boundingSphere.center,
            new Cesium.Cartesian3()
          );
          var heading = Cesium.Math.toRadians(230.0);
          var pitch = Cesium.Math.toRadians(-20.0);
          camera.lookAt(
            center,
            new Cesium.HeadingPitchRange(heading, pitch, r * 2.0)
          );
        })
        .otherwise(function(error) {
          alert(error.message);
        });
    }

    // 解锁锁定model视角
    function LookAtChange() {
      let model = window.model;
      var camera = window.viewer.camera;
      let scene = window.viewer.scene;
      var controller = scene.screenSpaceCameraController;
      var r = 2.0 * Math.max(model.boundingSphere.radius, camera.frustum.near);
      controller.minimumZoomDistance = r * 0.5;

      var center = Cesium.Matrix4.multiplyByPoint(
        model.modelMatrix,
        model.boundingSphere.center,
        new Cesium.Cartesian3()
      );
      var heading = Cesium.Math.toRadians(230.0);
      var pitch = Cesium.Math.toRadians(-20.0);
      camera.lookAt(
        center,
        new Cesium.HeadingPitchRange(heading, pitch, r * 2.0)
      );
    }
    // 点击显示坐标
    function ClickShowPosition() {
      let viewer = window.viewer;
      let scene = window.viewer.scene;
      let ellipsoid = viewer.scene.globe.ellipsoid;
      var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
      handler.setInputAction((event) => {
        var windowPostion = event.position;
        var cartesian3 = scene.globe.pick(
          viewer.camera.getPickRay(windowPostion),
          scene
        );
        // 三维笛卡尔空间直角坐标（世界坐标）转为二维屏幕坐标
        // 结果是Cartesian2对象，取出X,Y即为屏幕坐标。
        // windowPostion = Cesium.SceneTransforms.wgs84ToWindowCoordinates(
        //   scene,
        //   cartesian3
        // );

        // 3.笛卡尔空间直角坐标系转为地理坐标（弧度制）
        // var cartographic = Cesium.Cartographic.fromCartesian(cartesian3); // 方法1
        var cartographic = ellipsoid.cartesianToCartographic(cartesian3); // 方法2

        // 4.地理坐标（弧度制）转为经纬度坐标
        var lat = Cesium.Math.toDegrees(cartographic.latitude);
        var lng = Cesium.Math.toDegrees(cartographic.longitude);
        var height = cartographic.height;
        ElMessage(`经度：${lng}. 维度：${lat}. 高度：${height}米`); //单位：度，度，米

        // 经纬度转弧度
        // Cesium.Math.toRadians(lat);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    onMounted(() => {
      Initialize();
    });
    return { msg, ResetView, LookAtChange, JustifyHeight };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  /* margin-top: 60px; */
  position: relative;
  width: 100%;
  height: 100vh;
}

#test {
  width: 100%;
  height: 100%;
  right: 0px;
  position: absolute;
  z-index: 0;
}

#welcome {
  position: absolute;
  left: 20px;
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.5);
}
</style>
